package com.face.server.service.impl;

import com.face.server.convert.Student2NormStu;
import com.face.server.dao.JoinedDAO;
import com.face.server.dao.VisitorDAO;
import com.face.server.entity.Admin;
import com.face.server.entity.Dormitory;
import com.face.server.entity.DormitoryBuild;
import com.face.server.entity.Student;
import com.face.server.repository.DormitoryRepository;
import com.face.server.service.DormitoryService;
import com.face.server.repository.exRepository.exDormitoryRepository;
import com.face.server.vo.NormStu;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.management.Query;
import java.security.Principal;
import java.util.List;

/**
 * Created by ryan on 2018/3/15.
 */
@Service
public class DormitoryServiceImpl implements DormitoryService {
    @Autowired
    private DormitoryRepository dormitoryRepository;

    @Autowired
    private exDormitoryRepository exDormitoryRepository;

    @Autowired
    private JoinedDAO joinedDAO;

    @Autowired
    private VisitorDAO visitorDAO;


    @Override
    public Page<Dormitory> listDormitories(Pageable pageRequest, String key1, String key2) {
        if ((key1==null||key1.equals(""))&&(key2==null||key2.equals(""))){
            Page<Dormitory> dormitories=dormitoryRepository.findAll(pageRequest);
            return dormitories;
        }
        List<Dormitory> dormitories=exDormitoryRepository.listDormitories(pageRequest,key1,key2);
        return new PageImpl<Dormitory>(dormitories,pageRequest,dormitories.size());

    }

    @Override
    public List<NormStu> listStuInDorm(String id) {
        Dormitory dormitory=dormitoryRepository.findOne(id);
        int roomNum=dormitory.getRoomNumber();
        int buildNum=dormitory.getDormitoryBuildNum();
        List<Student> students=joinedDAO.listStuWithDorm(buildNum,roomNum);
        return Student2NormStu.convert(students);
    }

    @Override
    public Page<Dormitory> listDormitories(Pageable pageRequest, String key1, String key2, Principal principal) {
        Subject subject = SecurityUtils.getSubject();
        Admin admin = (Admin) subject.getPrincipal();
        List<Integer> dormitoryNumList=admin.getDormitoryNumList();
        if ((key1==null||key1.equals(""))&&(key2==null||key2.equals(""))){
            Page<Dormitory> dormitories=dormitoryRepository.findByDormitoryBuildNumIn(dormitoryNumList,pageRequest);
            return dormitories;
        }
        List<Dormitory> dormitories=exDormitoryRepository.listDormitories(pageRequest,key1,key2,dormitoryNumList);
        return new PageImpl<Dormitory>(dormitories,pageRequest,dormitories.size());
    }

}
